package com.huikeportal.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huikeportal.dao.LoginMapper;
import com.huikeportal.dao.RoleMapper;
import com.huikeportal.model.MenuInfo;
import com.huikeportal.model.RolePageButton;
import com.huikeportal.model.TreeHtml;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.RoleApiService;

@Service("roleApiService")
public class RoleApiServiceImpl implements RoleApiService {

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private LoginMapper loginMapper;

	// 树节点深度
	private int loop = -1;

	// 角色列表的条数
	private int size = 0;

	/**
	 * 获取角色树html
	 */
	public String getRoleListHtml(String userId, String roleId)
			throws Exception {
		UserInfo userInfo = new UserInfo();
		userInfo.setUserId(userId);
		Long id = roleMapper.getRoleIdByUser(userInfo.getUserId());
		userInfo.setId(id);
		List<TreeHtml> roleList = roleMapper.getRoleById(userInfo);
		size = roleList.size();
		roleList = getFloor(roleList);
		return createTreeHtml(roleList, userInfo.getId(), roleId);
	}

	/**
	 * 获取每一层树节点的层数
	 * 
	 * @param floorList
	 * @return
	 */
	private List<TreeHtml> getFloor(List<TreeHtml> floorList) {
		for (int i = 0; i < floorList.size(); i++) {
			// 如果未处理
			if (!floorList.get(i).isDeal()) {
				loop = -1;
				int k = getFl(floorList, floorList.get(i));
				floorList.get(i).setFloorNum(k);
				// 将该节点设为已处理
				floorList.get(i).setDeal(true);
				size--;
			}
		}
		return floorList;
	}

	/**
	 * 递归获取树节点深度
	 * 
	 * @param floorList
	 * @param treeHtml
	 * @return
	 */
	private int getFl(List<TreeHtml> floorList, TreeHtml treeHtml) {
		loop++;
		// 如果当前处理的节点不是根节点，则继续处理他的父节点
		if (treeHtml.getParentId() != 0) {
			for (int i = 0; i < floorList.size(); i++) {
				if (treeHtml.getParentId().equals(floorList.get(i).getId())) {
					treeHtml = floorList.get(i);
					return getFl(floorList, treeHtml);
				}
			}
		}
		return loop;
	}

	/**
	 * 根据角色列表生成html
	 * 
	 * @param roleList
	 *            当前用户拥有的角色清单(包含其下级角色创建的角色清单)
	 * @param id
	 *            当前用户拥有的主角色
	 * @return
	 */
	private String createTreeHtml(List<TreeHtml> roleList, Long id,
			String roleId) {
		// 全部树节点存储容器
		Map<String, TreeHtml> allMap = new HashMap<String, TreeHtml>();
		// 全部子节点列表存储容器
		Map<String, TreeHtml> childMap = new HashMap<String, TreeHtml>();
		String treeHtml = "";
		// 如果当前用户只有一个角色
		if (roleList.size() == 1) {
			treeHtml = "<li id='role_" + roleList.get(0).getRoleId()
					+ "' onclick='showpriv(\"" + roleList.get(0).getRoleId()
					+ "\")'><span>" + roleList.get(0).getRoleName()
					+ "</span></li>";
		}
		// 如果当前用户有下级角色
		else {
			for (int i = 0; i < roleList.size(); i++) {
				allMap.put(roleList.get(i).getId().toString(), roleList.get(i));
			}
			// 生成根节点html
			TreeHtml rootHtml = new TreeHtml();
			rootHtml.setId(id);
			// 循环角色列表，合并，并删除allMap中的值
			while (allMap.size() > 1) {
				for (int i = 0; i < roleList.size(); i++) {
					// 根节点不处理
					if (!id.equals(roleList.get(i).getId())) {
						// 如果该节点还未被处理过
						if (allMap.containsKey(roleList.get(i).getId()
								.toString())) {
							// 从allMap中获取该节点的最新信息
							TreeHtml childHtml = allMap.get(roleList.get(i)
									.getId().toString());
							// 如果该节点是叶子，将其父节点放入容器中，且将其父节点变成叶子
							if (childHtml.isLeaf()) {
								TreeHtml fatherHtml = new TreeHtml();
								// 找到其父节点
								for (int j = 0; j < roleList.size(); j++) {
									if (childHtml.getParentId().equals(
											roleList.get(j).getId())) {
										fatherHtml = roleList.get(j);
										break;
									}
								}
								String fatherKey = fatherHtml.getId()
										.toString();
								// 如果该父节点还未在容器中，则加入，并更改状态
								if (!childMap.containsKey(fatherKey)) {
									fatherHtml.setLeaf(true);
									List<TreeHtml> chiList = new ArrayList<TreeHtml>();
									chiList.add(childHtml);
									fatherHtml.setChildHtml(chiList);
									childMap.put(fatherHtml.getId().toString(),
											fatherHtml);

								}
								// 如果该父节点已经在容器中，则加入其子节点集合中
								else {
									fatherHtml = childMap.get(fatherKey);
									List<TreeHtml> chiList = fatherHtml
											.getChildHtml();
									chiList.add(childHtml);
									childMap.remove(fatherKey);
									childMap.put(fatherHtml.getId().toString(),
											fatherHtml);
								}
								allMap.remove(childHtml.getId().toString());
							}
						}
					}
				}
			}
			// 获取根节点信息，生成html
			TreeHtml root = allMap.get(id.toString());
			treeHtml = "<ul>";
			treeHtml += createChildHtml(root, roleId);
			treeHtml += "</ul>";
		}
		return treeHtml;
	}

	/**
	 * 递归生成treehtml
	 * 
	 * @param tree
	 * @return
	 */
	private String createChildHtml(TreeHtml tree, String roleId) {
		String html = "";
		if (tree.getChildHtml() != null) {
			if (tree.getRoleId().equals(roleId)) {
				html += "<li id='role_"
						+ tree.getRoleId()
						+ "'><div class='floatL'>"
						+ space(tree.getFloorNum())
						+ "</div><div class='shouqi' onclick='showhide(\""
						+ tree.getRoleId()
						+ "\")'></div><span class='orange' onclick='showpriv(\""
						+ tree.getRoleId() + "\")'>" + tree.getRoleName()
						+ "</span><ul id='role_" + tree.getRoleId() + "_li'>";
			} else {
				html += "<li id='role_" + tree.getRoleId()
						+ "'><div class='floatL'>" + space(tree.getFloorNum())
						+ "</div><div class='shouqi' onclick='showhide(\""
						+ tree.getRoleId()
						+ "\")'></div><span onclick='showpriv(\""
						+ tree.getRoleId() + "\")'>" + tree.getRoleName()
						+ "</span><ul id='role_" + tree.getRoleId() + "_li'>";
			}
			for (int i = 0; i < tree.getChildHtml().size(); i++) {
				html += createChildHtml(tree.getChildHtml().get(i), roleId);
			}
			html += "</ul></li>";
		} else {
			if (tree.getRoleId().equals(roleId)) {
				html += "<li id='role_" + tree.getRoleId()
						+ "'><div class='floatL'>" + space(tree.getFloorNum())
						+ "</div><span class='orange' onclick='showpriv(\""
						+ tree.getRoleId() + "\")'>" + tree.getRoleName()
						+ "</span></li>";
			} else {
				html += "<li id='role_" + tree.getRoleId()
						+ "'><div class='floatL'>" + space(tree.getFloorNum())
						+ "</div><span onclick='showpriv(\"" + tree.getRoleId()
						+ "\")'>" + tree.getRoleName() + "</span></li>";
			}
		}
		return html;
	}

	/**
	 * 树节点空格数
	 * 
	 * @param loop
	 * @return
	 */
	private String space(int loop) {
		String space = "";
		for (int i = 0; i < loop; i++) {
			space += "&nbsp;&nbsp;";
		}
		return space;
	}

	/**
	 * 获取页面信息
	 * 
	 * @param flag
	 * @return
	 * @throws Exception
	 */
	public List<MenuInfo> getPageInfo(String flag,
			List<RolePageButton> roleHtml, String sysLang) throws Exception {
		List<MenuInfo> resultList = new ArrayList<MenuInfo>();
		if ("1".equals(flag)) {
			SqlParameter sql = new SqlParameter();
			sql.setString("12");
			sql.setSysLang(sysLang);
			List<MenuInfo> oneList = loginMapper.getMenuListByType(sql);
			if ("".equals(roleHtml) || roleHtml == null) {
				return oneList;
			}
			for (int i = 0; i < oneList.size(); i++) {
				for (int j = 0; j < roleHtml.size(); j++) {
					if (oneList.get(i).getMenuId().equals(
							roleHtml.get(j).getParentId())) {
						resultList.add(oneList.get(i));
						break;
					}
				}
			}
			// 菜单过滤
			return resultList;
		} else if ("2".equals(flag)) {
			SqlParameter sql = new SqlParameter();
			sql.setString("13");
			sql.setSysLang(sysLang);
			List<MenuInfo> twoList = loginMapper.getMenuListByType(sql);
			if ("".equals(roleHtml) || roleHtml == null) {
				return twoList;
			}
			for (int i = 0; i < twoList.size(); i++) {
				for (int j = 0; j < roleHtml.size(); j++) {
					if (twoList.get(i).getMenuId().equals(
							roleHtml.get(j).getMenuId())) {
						resultList.add(twoList.get(i));
						break;
					}
				}
			}
			// 菜单过滤
			return resultList;
		} else {
			return null;
		}
	}

}
